/*
 * Copyright 2013 Rivaldo.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jety.server;

import com.google.gson.JsonObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jety.commons.util.JsonConverter;
import org.jety.commons.util.JsonRpcErrorBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Rivaldo
 */
public class JsonRpcServerTransport {

    private static final Logger LOG = LoggerFactory.getLogger(JsonRpcServerTransport.class);

    private static final int BUFF_LENGTH = 1024;

    private final HttpServletRequest req;
    private final HttpServletResponse resp;

    public JsonRpcServerTransport(HttpServletRequest req, HttpServletResponse resp) {
        this.req = req;
        this.resp = resp;
    }

    public void writeResponse(String responseData) throws UnsupportedEncodingException, IOException {
        write(responseData, resp);
    }

    public JsonObject readRequest() throws Exception {

        JsonObject request = null;
        try {
            String requestData = read(req);
            LOG.debug("JSON-RPC >>  {}", requestData);
            request = JsonConverter.toJsonObject(requestData);
        } catch (IOException ex) {
            sendRequestError(ex);
            throw ex;
        }

        return request;
    }

    //<editor-fold defaultstate="collapsed" desc="Leitura e escrita">
    public String read(HttpServletRequest request) throws IOException {

        InputStream in = null;

        try {
            in = request.getInputStream();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            byte[] buff = new byte[BUFF_LENGTH];
            int n;
            while ((n = in.read(buff)) > 0) {
                bos.write(buff, 0, n);
            }

            //bos.flush();
            //bos.close();

            return bos.toString();
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }

    public void write(String responseData, HttpServletResponse response) throws UnsupportedEncodingException, IOException {

        byte[] data = responseData.getBytes(response.getCharacterEncoding());
        response.addHeader("Content-Type", "application/json");
        response.setHeader("Content-Length", Integer.toString(data.length));

        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.write(responseData);
            out.flush();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Envio de erros">
    private void sendRequestError(Throwable exception) throws UnsupportedEncodingException, IOException {
        String error = JsonRpcErrorBuilder.getRequestParseError(exception);
        LOG.debug("JSON-RPC error <<  {}", error);
        write(error, resp);
    }

    private void sendInvalidRequestError(int requestID, Throwable exception) throws UnsupportedEncodingException, IOException  {
        String error = JsonRpcErrorBuilder.getInvalidRequestError(requestID, exception);
        LOG.debug("JSON-RPC error <<  {}", error);
        write(error, resp);
    }
    //</editor-fold>

    public HttpServletRequest getRequest() {
        return req;
    }

    public HttpServletResponse getResponse() {
        return resp;
    }
}
